package com.An.conf;

import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale;

/**
 * @auther AnYang
 * @date 2022/3/24 18:11
 **/
public class MyLocaleResolve implements LocaleResolver {
	//解析请求
	private static final String I18N_LANGUAGE = "lang";
	private static final String I18N_LANGUAGE_SESSION = "lang_session";

	@Override
	public Locale resolveLocale(HttpServletRequest request) {
		//获取请求中的语言参数
		String language = request.getParameter(I18N_LANGUAGE);
		Locale locale = Locale.getDefault();//如果没有就使用默认的
		if (!StringUtils.isEmpty(language)) {
			//判断language是否为空,如果不为空，匹配对应的语言
			String[] split = language.split("_");
			locale = new Locale(split[0], split[1]);
			HttpSession session = request.getSession();
			session.setAttribute(I18N_LANGUAGE_SESSION, locale);
		} else {
			HttpSession session = request.getSession();
			Locale localeInSession = (Locale) session.getAttribute(I18N_LANGUAGE_SESSION);
			if (localeInSession != null) {
				locale = localeInSession;
			}
		}

		return locale;
	}

	@Override
	public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

	}
}